package com.prism.e4.rcp.ui.handlers;

import java.io.File;

import javax.inject.Named;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.ui.model.application.MApplication;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.prism.e4.rcp.ui.parts.E4PrismEditor;

//adapt to pepa file
public class NewPepaModelHandler {

	@Execute
	public void execute(
			@Named(IServiceConstants.ACTIVE_SHELL) Shell parentShell,
			MApplication application, EModelService modelService,
			final EPartService partService, final IWorkspace workspace,
			final IProgressMonitor monitor) {

		MPart existedPart = (MPart) modelService.find(
				"com.prism.e4.rcp.inputpart", application);
		if (!existedPart.isVisible())
			existedPart.setVisible(true);
		E4PrismEditor editor = (E4PrismEditor) existedPart.getObject();

		if (editor.dirty.isDirty()) {
			MessageDialog dialog = new MessageDialog(parentShell, "Question",
					null, "Model has been modified. Do you wish to save it?",
					MessageDialog.QUESTION, new String[] { "Yes", "No",
							"Cancel" }, 0);
			int returnCode = dialog.open();
			if (returnCode == 0) {
				FileDialog fDialog = new FileDialog(parentShell, SWT.SAVE);
				fDialog.setFilterNames(new String[] {"All Files (*.*)"});
				fDialog.setFilterExtensions(new String[] {"*.*"});				
				String fileName = fDialog.open();
				if(fileName == null) return;
				if(new File(fileName).exists()) {
					MessageBox mb = new MessageBox(fDialog.getParent(),SWT.ICON_WARNING | SWT.YES | SWT.NO);
				    mb.setMessage(fileName + " already exists, do you want to replace it?");
				    if (mb.open() == SWT.NO)     return;
				}
				// TODO: saving to file with a given fileName
				existedPart.setLabel("PEPAModel.pepa");
				clear(editor);
			} else if (returnCode == 1) {
				existedPart.setLabel("PEPAModel.pepa");
				clear(editor);
			}
		} else {
			existedPart.setLabel("PEPAModel.pepa");
			clear(editor);
		}
	}
	
	private void clear(E4PrismEditor editor) {
		editor.editorService.sellectAll();
		editor.editorService.delete();
		editor.dirty.setDirty(false);
	}
}
